class User < ActiveRecord::Base

    include Account::AccountModel
    
    has_many :annorations
    
	##########################################################
	# Gets tags applied by a user to an entry
    # 
    def tags_for_page(page_id)
        tags = tag_list_for_page(page_id)
        tag_list = ""
        tags.each {|tag| tag_list << tag.name + " "} if tags
        return tag_list
    end

    def tag_list_for_page(page_id)
        sql = "SELECT tags.name FROM tags "
        sql << "INNER JOIN pages_tags ON pages_tags.tag_id = tags.id "
        sql << "WHERE pages_tags.user_id = ? AND pages_tags.page_id = ? "
        sql << "ORDER BY lower(tags.name)"
        Tag.find_by_sql([sql, self.id, page_id])
    end
    
    ##########################################################
	# Finds suggested tags for a user and a entry 
	# maps from story to its tags to other stories those tags have been applied to
	# and then to tags that the user has applied to those stories
    # 
	def suggested_tags_for_page(page_id, options = {})
        sql = "SELECT DISTINCT ON(lower(t2.name), et3.tag_id) t2.name, t2.id "
        sql << "FROM pages_tags et1 "
        sql << "INNER JOIN tags t1 ON et1.tag_id = t1.id "
        sql << "INNER JOIN pages_tags et2 ON t1.id = et2.tag_id "
        sql << "INNER JOIN pages_tags et3 ON et2.page_id = et3.page_id "
        sql << "INNER JOIN tags t2 ON et3.tag_id = t2.id "
        sql << "WHERE et3.user_id = ? AND et1.page_id = ?"
        sql << "ORDER BY lower(t2.name), et3.tag_id"
        add_limit!(sql, options)
        User.find_by_sql([sql, self.id, page_id])
    end

    def add_limit!(sql, options = {})
        if limit = options[:limit]
            sql << " LIMIT #{limit}"
            if offset = options[:offset]
                sql << " OFFSET #{offset}"
            end
        end
    end
        
end
